package com.chixing.service.impl;

import com.chixing.entity.Member;
import com.chixing.mapper.MemberMapper;
import com.chixing.service.IMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liwenjing
 * @since 2025-10-07
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member>  implements IMemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Member getMemberByUserId(Integer userId) {
        return memberMapper.getMemberByUserId(userId);
    }

    @Override
    @Transactional
    public void addPointsOnPaymentSuccess(Integer userId, Double price) {
        Member member = memberMapper.getMemberByUserId(userId);
        if (member == null) return;

        int newPoints = (int) (member.getMembershipPoints() + price.intValue());
        memberMapper.updateMemberPoints(userId, newPoints);
    }

    @Override
    @Transactional
    public void deductPointsOnRefund(Integer userId, Double price) {
        Member member = memberMapper.getMemberByUserId(userId);
        if (member == null) return;

        int newPoints = (int) (member.getMembershipPoints() - price.intValue());
        if (newPoints < 0) newPoints = 0; // 积分不能负数

        memberMapper.updateMemberPoints(userId, newPoints);
    }
}
